package com.doingnow.zuul.common;

import com.doingnow.zuul.microservice.UcenterService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Component
public class CustomZuulFilter extends ZuulFilter {

    @Autowired
    private UcenterService ucenterService;

    private List<String> excludePaths = Arrays.asList("/oauth/token");

    private RouteLocator routeLocator;
    private ZuulProperties properties;
    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    public CustomZuulFilter(RouteLocator routeLocator, ZuulProperties properties) {
        this.routeLocator = routeLocator;
        this.properties = properties;
        this.urlPathHelper.setRemoveSemicolonContent(properties.isRemoveSemicolonContent());
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.getResponse().setCharacterEncoding("UTF-8");
        ctx.getResponse().setContentType("text/json; charset=utf-8");
        HttpServletRequest request = ctx.getRequest();
        String requestURI = this.urlPathHelper.getPathWithinApplication(request);
        Route route = this.routeLocator.getMatchingRoute(requestURI);
        if (route.getId().equals("ucenter")
                && excludePaths.contains(route.getPath())
                && request.getMethod().equals("POST")) {
            ctx.setSendZuulResponse(true);// 对该请求进行路由
            ctx.setResponseStatusCode(200);
            return null;
        }
        String token = request.getParameter("token");// 获取请求的参数
        if (null != token && ucenterService.checkToken(token)) {// 如果请求的参数不为空，且值为chhliu时，则通过
            ctx.setSendZuulResponse(true);// 对该请求进行路由
            ctx.setResponseStatusCode(200);
        } else {
            ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
            ctx.setResponseStatusCode(401);// 返回错误码
            ResponseError responseError = new ResponseError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED, "没有token参数或token无效", request.getContextPath(), null, "没有token参数或token无效");
            ctx.setResponseBody(responseError.toJsonString());// 返回错误内容
        }
        return null;
    }

    @Override
    public boolean shouldFilter() {
        return true;// 是否执行该过滤器，此处为true，说明需要过滤  
    }

    @Override
    public int filterOrder() {
        return 0;// 优先级为0，数字越大，优先级越低  
    }

    @Override
    public String filterType() {
        return "pre";// 前置过滤器
    }
}  